import SwiftUI

@main
struct ElderlyCareApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @StateObject private var viewModel = ElderlyCareViewModel()
    
    var body: some View {
        TabView {
            ServiceListView()
                .tabItem {
                    Label("服务列表", systemImage: "list.bullet")
                }
            
            DemandView()
                .tabItem {
                    Label("需求匹配", systemImage: "person.badge.plus")
                }
            
            MapView()
                .tabItem {
                    Label("地图", systemImage: "map")
                }
            
            StatisticsView()
                .tabItem {
                    Label("统计", systemImage: "chart.bar")
                }
        }
        .environmentObject(viewModel)
    }
}

class ElderlyCareViewModel: ObservableObject {
    @Published var providers: [CareProvider] = []
    @Published var demands: [ElderlyDemand] = []
    @Published var matches: [(demand: ElderlyDemand, provider: CareProvider)] = []
    
    private let dispatchSystem = ElderlyCareDispatchSystem()
    
    init() {
        loadSampleData()
    }
    
    func loadSampleData() {
        dispatchSystem.loadSampleData()
        
        // 同步数据到视图模型
        let stats = dispatchSystem.getStatistics()
        print("加载数据：\(stats.totalProviders) 个服务提供者，\(stats.totalDemands) 个需求")
    }
    
    func processMatches() {
        matches = dispatchSystem.processAllPendingDemands()
        objectWillChange.send()
    }
    
    func addProvider(_ provider: CareProvider) {
        dispatchSystem.addProvider(provider)
    }
    
    func addDemand(_ demand: ElderlyDemand) {
        dispatchSystem.addDemand(demand)
    }
    
    func getStatistics() -> (totalProviders: Int, totalDemands: Int, pendingDemands: Int, matchedDemands: Int) {
        return dispatchSystem.getStatistics()
    }
}

// MARK: - 服务列表视图
struct ServiceListView: View {
    @EnvironmentObject var viewModel: ElderlyCareViewModel
    
    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.providers, id: \.self) { provider in
                    ServiceProviderCard(provider: provider)
                }
            }
            .navigationTitle("服务提供者")
            .toolbar {
                Button(action: {
                    // 添加新服务提供者
                }) {
                    Image(systemName: "plus")
                }
            }
        }
    }
}

struct ServiceProviderCard: View {
    let provider: CareProvider
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Image(systemName: provider.type.iconName)
                    .font(.title2)
                    .foregroundColor(.blue)
                
                VStack(alignment: .leading) {
                    Text(provider.name)
                        .font(.headline)
                    Text(provider.type.rawValue)
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                HStack {
                    Image(systemName: "star.fill")
                        .foregroundColor(.yellow)
                    Text(String(format: "%.1f", provider.rating))
                        .font(.subheadline)
                }
            }
            
            HStack {
                Label(String(format: "%.1f km", provider.location.latitude), systemImage: "mappin")
                Spacer()
                if let rate = provider.hourlyRate {
                    Text("¥\(Int(rate))/小时")
                        .font(.subheadline)
                        .foregroundColor(.green)
                }
            }
            
            Text(provider.description)
                .font(.caption)
                .foregroundColor(.secondary)
                .lineLimit(2)
            
            // 生态评分
            EcoScoreView(scores: provider.ecoScores)
        }
        .padding(.vertical, 8)
    }
}

// MARK: - 需求匹配视图
struct DemandView: View {
    @EnvironmentObject var viewModel: ElderlyCareViewModel
    @State private var showingAddDemand = false
    
    var body: some View {
        NavigationView {
            List {
                Section(header: Text("待匹配需求")) {
                    ForEach(viewModel.demands.filter { $0.status == .pending }, id: \.id) { demand in
                        DemandCard(demand: demand)
                    }
                }
                
                Section(header: Text("已匹配需求")) {
                    ForEach(viewModel.matches, id: \.demand.id) { match in
                        MatchedDemandCard(demand: match.demand, provider: match.provider)
                    }
                }
            }
            .navigationTitle("需求管理")
            .toolbar {
                Button(action: {
                    showingAddDemand = true
                }) {
                    Image(systemName: "plus")
                }
                
                Button(action: {
                    viewModel.processMatches()
                }) {
                    Image(systemName: "arrow.triangle.2.circlepath")
                }
            }
            .sheet(isPresented: $showingAddDemand) {
                AddDemandView()
            }
        }
    }
}

struct DemandCard: View {
    let demand: ElderlyDemand
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Image(systemName: demand.type.iconName)
                    .font(.title2)
                    .foregroundColor(.orange)
                
                VStack(alignment: .leading) {
                    Text(demand.type.rawValue)
                        .font(.headline)
                    Text("紧急程度：\(demand.urgency.rawValue)")
                        .font(.subheadline)
                        .foregroundColor(demand.urgency == .high ? .red : .secondary)
                }
                
                Spacer()
                
                Text(demand.status.rawValue)
                    .font(.caption)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(Color.blue.opacity(0.2))
                    .cornerRadius(8)
            }
            
            if !demand.specialRequirements.isEmpty {
                Text("特殊需求：\(demand.specialRequirements.joined(separator: "、"))")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            if let budget = demand.budget {
                Text("预算：¥\(Int(budget))")
                    .font(.subheadline)
                    .foregroundColor(.green)
            }
            
            Text("创建时间：\(demand.createdAt, formatter: dateFormatter)")
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .padding(.vertical, 8)
    }
}

struct MatchedDemandCard: View {
    let demand: ElderlyDemand
    let provider: CareProvider
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Image(systemName: "checkmark.circle.fill")
                    .foregroundColor(.green)
                
                VStack(alignment: .leading) {
                    Text("已匹配：\(provider.name)")
                        .font(.headline)
                    Text(demand.type.rawValue)
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            }
            
            HStack {
                Text("距离：\(String(format: "%.1f", provider.distance(from: demand.location))) km")
                Spacer()
                Text("评分：\(String(format: "%.1f", provider.rating))")
            }
            .font(.caption)
            .foregroundColor(.secondary)
        }
        .padding(.vertical, 8)
    }
}

// MARK: - 地图视图
struct MapView: View {
    @EnvironmentObject var viewModel: ElderlyCareViewModel
    
    var body: some View {
        VStack {
            Text("地图视图")
                .font(.title)
            
            // 简化的地图表示
            ScrollView {
                VStack(spacing: 20) {
                    ForEach(viewModel.providers, id: \.self) { provider in
                        MapPinView(provider: provider)
                    }
                }
                .padding()
            }
        }
    }
}

struct MapPinView: View {
    let provider: CareProvider
    
    var body: some View {
        HStack {
            Image(systemName: "mappin.circle.fill")
                .font(.title)
                .foregroundColor(.red)
            
            VStack(alignment: .leading) {
                Text(provider.name)
                    .font(.headline)
                Text("纬度：\(String(format: "%.4f", provider.location.latitude))")
                    .font(.caption)
                Text("经度：\(String(format: "%.4f", provider.location.longitude))")
                    .font(.caption)
            }
            
            Spacer()
            
            Image(systemName: provider.type.iconName)
                .font(.title2)
                .foregroundColor(.blue)
        }
        .padding()
        .background(Color.gray.opacity(0.1))
        .cornerRadius(10)
    }
}

// MARK: - 统计视图
struct StatisticsView: View {
    @EnvironmentObject var viewModel: ElderlyCareViewModel
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 20) {
                    let stats = viewModel.getStatistics()
                    
                    StatCard(
                        title: "服务提供者",
                        value: "\(stats.totalProviders)",
                        icon: "person.2.fill",
                        color: .blue
                    )
                    
                    StatCard(
                        title: "总需求",
                        value: "\(stats.totalDemands)",
                        icon: "list.bullet",
                        color: .orange
                    )
                    
                    StatCard(
                        title: "待匹配",
                        value: "\(stats.pendingDemands)",
                        icon: "clock",
                        color: .red
                    )
                    
                    StatCard(
                        title: "已匹配",
                        value: "\(stats.matchedDemands)",
                        icon: "checkmark.circle.fill",
                        color: .green
                    )
                    
                    Button(action: {
                        viewModel.processMatches()
                    }) {
                        HStack {
                            Image(systemName: "arrow.triangle.2.circlepath")
                            Text("重新匹配")
                        }
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                    }
                }
                .padding()
            }
            .navigationTitle("系统统计")
        }
    }
}

struct StatCard: View {
    let title: String
    let value: String
    let icon: String
    let color: Color
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text(title)
                    .font(.headline)
                    .foregroundColor(.secondary)
                Text(value)
                    .font(.largeTitle)
                    .bold()
            }
            
            Spacer()
            
            Image(systemName: icon)
                .font(.largeTitle)
                .foregroundColor(color)
        }
        .padding()
        .background(Color.gray.opacity(0.1))
        .cornerRadius(10)
    }
}

// MARK: - 添加需求视图
struct AddDemandView: View {
    @EnvironmentObject var viewModel: ElderlyCareViewModel
    @Environment(\.presentationMode) var presentationMode
    
    @State private var selectedType = ElderlyCareServiceType.homeNursing
    @State private var urgency = UrgencyLevel.medium
    @State private var specialRequirements = ""
    @State private var budget = ""
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("服务类型")) {
                    Picker("服务类型", selection: $selectedType) {
                        ForEach(ElderlyCareServiceType.allCases, id: \.self) { type in
                            Text(type.rawValue).tag(type)
                        }
                    }
                }
                
                Section(header: Text("紧急程度")) {
                    Picker("紧急程度", selection: $urgency) {
                        ForEach(UrgencyLevel.allCases, id: \.self) { level in
                            Text(level.rawValue).tag(level)
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                
                Section(header: Text("特殊需求")) {
                    TextField("输入特殊需求，用逗号分隔", text: $specialRequirements)
                }
                
                Section(header: Text("预算")) {
                    TextField("预算金额", text: $budget)
                        .keyboardName(.decimalPad)
                }
            }
            .navigationTitle("添加需求")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        presentationMode.wrappedValue.dismiss()
                    }
                }
                
                ToolbarItem(placement: .confirmationAction) {
                    Button("添加") {
                        addDemand()
                    }
                }
            }
        }
    }
    
    private func addDemand() {
        let newDemand = ElderlyDemand(
            id: UUID(),
            elderId: "USER_\(Int.random(in: 1000...9999))",
            type: selectedType,
            urgency: urgency,
            location: CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074),
            startTime: Date().timeIntervalSince1970 + 3600,
            endTime: Date().timeIntervalSince1970 + 7200,
            specialRequirements: specialRequirements.components(separatedBy: ",").map { $0.trimmingCharacters(in: .whitespaces) },
            preferredEcoScores: nil,
            matchedProvider: nil,
            status: .pending,
            createdAt: Date(),
            budget: Double(budget) ?? 0
        )
        
        viewModel.addDemand(newDemand)
        presentationMode.wrappedValue.dismiss()
    }
}

// MARK: - 生态评分视图
struct EcoScoreView: View {
    let scores: EcoScores
    
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text("生态评分")
                .font(.caption)
                .foregroundColor(.secondary)
            
            HStack(spacing: 20) {
                ScoreItem(title: "环境", value: scores.environmental, color: .green)
                ScoreItem(title: "社会", value: scores.social, color: .blue)
                ScoreItem(title: "经济", value: scores.economic, color: .orange)
            }
        }
    }
}

struct ScoreItem: View {
    let title: String
    let value: Double
    let color: Color
    
    var body: some View {
        VStack {
            Text(title)
                .font(.caption)
            Text("\(Int(value))")
                .font(.caption.bold())
                .foregroundColor(color)
        }
    }
}

// MARK: - 工具扩展
private let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .short
    return formatter
}()

// MARK: - 预览
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(ElderlyCareViewModel())
    }
}